﻿using System.Windows;
using Store.WP7.Data;
using Store.WP7.Framework.ErrorManagement;
using System.Linq;

namespace Store.WP7.ViewModels
{
    public class ProductDetailsViewModel : PageViewModelBase
    {
        private readonly StoreService _storeService;
        private int _productId = 0;
        private bool _productIsLoaded;

        private ProductViewModel _productViewModel;
        public ProductViewModel ProductViewModel
        {
            get { return _productViewModel; }
            set
            {
                _productViewModel = value;
                RaisePropertyChanged(() => ProductViewModel);
            }
        }

        public ProductDetailsViewModel()
        {
            _storeService = new StoreService();
        }

        public override void OnNavigatedTo(System.Windows.Navigation.NavigationService navigationService, System.Windows.Navigation.NavigationContext navigationContext, System.Collections.Generic.IDictionary<string, object> state, System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(navigationService, navigationContext, state, e);

            if (!NavigationContext.QueryString.ContainsKey("productId") || !int.TryParse(NavigationContext.QueryString["productId"].ToString(), out _productId))
            {
                NavigationService.GoBack();
                return;
            }

            if (_productId != 0 && !_productIsLoaded)
            {
                // Try to load the ProductViewModel via a cached product so the data
                // is already loaded when the continuum effect is animating
                var product = StoreCache.Instance.Products.Where(p => p.Id == _productId).FirstOrDefault();
                if (product != null)
                    ProductViewModel = new ProductViewModel(product);

                LoadProduct();
            }
        }

        private void LoadProduct()
        {
            if (!IsBusy)
            {
                IsBusy = true;
                BusyMessage = "chargement du produit...";
                _storeService.LoadProductAsync(_productId, serviceResult =>
                {
                    if (serviceResult.Error == null)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => 
                        {
                            ProductViewModel = new ProductViewModel(serviceResult.Result);
                            IsBusy = false;
                            BusyMessage = "";
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            IsBusy = false;
                            ErrorManager.HandleError(ErrorType.WebServiceCallbackFail, serviceResult.Error);
                        });
                    }
                });
            }
        }

        public void GoToBasketView()
        {
            NavigationService.Navigate(new System.Uri("/Views/MainPage.xaml?go=basket", System.UriKind.Relative));
        }


        public void AddToBasket()
        {
            NavigationService.Navigate(new System.Uri("/Views/MainPage.xaml?productId=" + _productId + "&go=basket", System.UriKind.Relative));
        }
    }
}
